#include "SQLiteDAOFactory.h"

SQLiteDAOFactory* SQLiteDAOFactory::instance = NULL;

SQLiteDAOFactory::SQLiteDAOFactory() {
	database = NULL;
	userDAO = NULL;
	contentDAO = NULL;
	preferenceDAO = NULL;
}

SQLiteDAOFactory::~SQLiteDAOFactory() {
	sqlite3_close(database);
	if (userDAO == NULL)
		delete userDAO;
	if (contentDAO == NULL)
		delete contentDAO;
	if (preferenceDAO == NULL)
		delete preferenceDAO;
}

void SQLiteDAOFactory::connect_db() {
	if (database != NULL)
		return;

	if (sqlite3_open(Configuration::get_property("db_name").c_str(), &database)
			!= SQLITE_OK)
		throw SQLiteException("Cannot connect do database");

	contentDAO = new SQLiteContentDAO(database);
	userDAO = new SQLiteUserDAO(database);
	preferenceDAO = new SQLitePreferenceDAO(database);
}

void SQLiteDAOFactory::disconnect_db() {
	if (database != NULL)
		sqlite3_close(database);
}

SQLiteDAOFactory* SQLiteDAOFactory::getInstance() {
	if (instance == NULL) {
		instance = new SQLiteDAOFactory();
	}

	return instance;
}

ContentDAO* SQLiteDAOFactory::getContentDAO() {
	return contentDAO;
}

UserDAO* SQLiteDAOFactory::getUserDAO() {
	return userDAO;
}

PreferenceDAO* SQLiteDAOFactory::getPreferenceDAO() {
	return preferenceDAO;
}
